package com.ecarx.camera.main.view;

import android.Manifest;
import android.app.AlertDialog;
import android.car.hardware.power.CarPowerManager;
import android.content.pm.PackageManager;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;

import com.ecarx.camera.service.DvrStateService;
import com.ecarx.camera.ui.main.MainFragment;
import com.ecarx.camera.utils.DialogUtils;
import com.ecarx.camera.utils.FragmentUtils;
import com.ecarx.camera.utils.LogUtils;
import com.ecarx.camera.utils.Utils;
import com.ecarx.camera.worker.car.aosp.AospCarManager;
import com.ecarx.camera.worker.car.sensor.SensorManager;

public class MainActivity extends AppCompatActivity {

    private static final String TAG = "MainActivity";

    private static final int PERMISSIONS_REQUEST_CODE = 10;
    private static final String[] PERMISSIONS_REQUIRED = {Manifest.permission.CAMERA, Manifest.permission.RECORD_AUDIO, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.ACCESS_COARSE_LOCATION};

    private SensorManager.AccOnChangedListener mAccOnChangedListener = new SensorManager.AccOnChangedListener() {
        @Override
        public void onAccOnChanged(boolean isAccOn) {
            LogUtils.d(TAG, "onAccOnChanged, " + isAccOn);
            if (!isAccOn) {
                doOnAccOff();
            } else {
                doOnAccOn();
            }
        }
    };
    private AlertDialog mAccOffDialog;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        LogUtils.d(TAG, "Lifecycle-> onCreate");
        checkAccOnState();
        SensorManager.get().registerAccOnChangedListener(mAccOnChangedListener);
        if (!hasPermissions()) {
            // Request camera-related permissions
            requestPermissions(PERMISSIONS_REQUIRED, PERMISSIONS_REQUEST_CODE);
        } else {
            // If permissions have already been granted, proceed
            navigate();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == PERMISSIONS_REQUEST_CODE) {
            for (int grantResult : grantResults) {
                if (grantResult == PackageManager.PERMISSION_DENIED) {
                    finish();
                    System.exit(0);
                    return;
                }
            }
            // Take the user to the success fragment when permission is granted
            navigate();
        }
    }

    @Override
    protected void onStart() {
        super.onStart();
        LogUtils.d(TAG, "Lifecycle-> onStart");
        DvrStateService.startIfNotRunning(this);
    }

    @Override
    protected void onResume() {
        super.onResume();
        LogUtils.d(TAG, "Lifecycle-> onResume");
    }

    @Override
    protected void onPause() {
        super.onPause();
        LogUtils.d(TAG, "Lifecycle-> onPause");
    }

    @Override
    protected void onStop() {
        super.onStop();
        LogUtils.d(TAG, "Lifecycle-> onStop");
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        LogUtils.d(TAG, "Lifecycle-> onDestroy");
        SensorManager.get().unregisterAccOnChangedListener(mAccOnChangedListener);
        if (mAccOffDialog != null && mAccOffDialog.isShowing()) {
            mAccOffDialog.dismiss();
        }
        AospCarManager.get().onDestroy();
    }

    private static boolean hasPermissions() {
        for (String permissionRequired : PERMISSIONS_REQUIRED) {
            if (ContextCompat.checkSelfPermission(Utils.getApp(), permissionRequired) == PackageManager.PERMISSION_DENIED) {
                return false;
            }
        }
        return true;
    }

    private void navigate() {
        bindSTRListener();
        MainFragment mainFragment = new MainFragment();
        mainFragment.setArguments(getIntent().getExtras());
        FragmentUtils.replace(getSupportFragmentManager(), mainFragment, android.R.id.content);
    }

    /**
     * 检测上电状态
     */
    private boolean checkAccOnState() {
        boolean isAccOn = SensorManager.get().isAccOn();
        if (!isAccOn) {
            doOnAccOff();
        }
        return isAccOn;
    }

    /**
     * 下电时的处理
     */
    private void doOnAccOff() {
        LogUtils.d(TAG, "doOnAccOff");
        if (mAccOffDialog != null && mAccOffDialog.isShowing()) {
            LogUtils.d(TAG, "doOnAccOff, dialog is already showing");
            return;
        }
        mAccOffDialog = DialogUtils.showAccOffDialog(MainActivity.this);
    }

    /**
     * 上电时的处理
     */
    private void doOnAccOn() {
        LogUtils.d(TAG, "doOnAccOn");
        if (mAccOffDialog != null && mAccOffDialog.isShowing()) {
            mAccOffDialog.dismiss();
        }
    }

    /**
     * STR 监听
     */
    private void bindSTRListener() {
        LogUtils.d(TAG, "bindSTRListener bind start setSTRStateListener");
        AospCarManager.get().setSTRStateListener(new AospCarManager.STRStateListener() {
            @Override
            public void onStateChanged(int state) {
                LogUtils.e(TAG, "bindSTRListener: state=" + state);
                if (state == CarPowerManager.CarPowerStateListener.SUSPEND_ENTER) {
                    forceFinish();
                }
            }
        });
    }

    /**
     * 强制关闭
     */
    private void forceFinish() {
        LogUtils.e(TAG, "bindSTR force finish");
        finish();
        System.exit(0);
    }
}
